package com.wf.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.domain.Menu;
import com.wf.dto.UserDTO;
import com.wf.mapper.MenuMapper;
import com.wf.service.MenuService;
import com.wf.utils.ValidateCodeUtils;
import com.wf.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: zhiyu
 * @Date:19:15
 * @DESC:
 */
@RestController
@Api("菜单管理控制层")
@CrossOrigin
public class MenuController {
    @Autowired
    private MenuService menuService;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @ApiOperation("根据菜单名和父菜单查询菜单，如果为空则查询所有")
    @GetMapping("/selectMenu")
    public Result selectMenu(@RequestParam(value = "menu_name",required = false) String menu_name, @RequestParam(value = "parent_id",required = false) Integer parent_id){
        List<Menu> menus = menuService.selectMenu(menu_name, parent_id);
        return Result.success(menus);
    }
    @ApiOperation("查询树状菜单")
    @GetMapping("/selectTreeMenu")
    public Result selectTreeMenu(){
        Boolean b = redisTemplate.hasKey("treeMenu");
        if (b){
            System.out.println("从缓存中拿数据");
            return Result.success(redisTemplate.opsForValue().get("treeMenu"));
        }else {
            List<Menu> menus = menuService.selectTreeMenu();
            redisTemplate.opsForValue().set("treeMenu",menus);
            System.out.println("调用方法拿数据再存入缓存中");
            return Result.success(menus);
        }
    }
    @ApiOperation("逻辑删除菜单")
    @DeleteMapping("/deleteMenu")
    public Result deleteMenu(@RequestParam(value = "menu_id",required = false) Integer menu_id){
        int i = menuMapper.deleteById(menu_id);
        boolean flag = false;
        if (i>0){
            flag = true;
            redisTemplate.delete("treeMenu");
        }
        return Result.success(flag);
    }
    @ApiOperation("添加菜单")
    @PutMapping("/addMenu")
    public Result addMenu(@RequestBody Menu menu){
        System.out.println("menu = " + menu);
        int i = menuMapper.insert(menu);
        boolean flag = false;
        if (i>0){
            flag = true;
            redisTemplate.delete("treeMenu");
        }
        return Result.success(flag);
    }
    @ApiOperation("修改菜单")
    @PostMapping("/editMenu")
    public Result editMenu(@RequestBody Menu menu){
//        System.out.println("menu = " + menu);
        int i = menuMapper.updateById(menu);
        if (i>0){
            return Result.success(true);
        }else {
            return Result.success(false);
        }
    }
}
